let newsData = require('../../../data/data.js').postList;
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    playing:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      news: newsData[options.id],
      id: options.id
    });
    this.getCollection();

    this.setMusicManage();
    
    // 全局变量赋值到page
    if (app.globalData.musicId == options.id) { 
      this.setData({ playing: app.globalData.musicPlaying });
    }
  },

  //设置播放状态
  setMusicManage: function() {
    let manager = wx.getBackgroundAudioManager();
    // 监听播放
    manager.onPlay(() => {
      this.setData({ playing: true });
      app.globalData.musicPlaying = true;
      app.globalData.musicId = this.data.id;
    });
     // 监听暂停
    manager.onPause(() => {
      this.setData({ playing: false });
      app.globalData.musicPlaying = false;
    });
     // 监听停止
    manager.onStop(() => {
      this.setData({ playing: false });
      app.globalData.musicPlaying = false;
    });
    // 监听结束
    manager.onEnded(() => {
      this.setData({ playing: false });
      app.globalData.musicPlaying = false;
    });
  },

  // 获取收藏数据
  getCollection: function() {
    let collection = wx.getStorageSync('collection');
    let currentCollection = collection && collection[this.data.id];
    this.setData({
      currentCollection
    });
  },

  // 是否收藏模态框
  showModal: function() {
    let currentCollection = this.data.currentCollection;
    wx.showModal({
      title: '收藏',
      content: !currentCollection ? '收藏该文章' : '取消收藏该文章',
      showCancel: true,
      cancelText: '取消',
      confirmText: '确认',
      success: (res) => {
        if (res.confirm) {
          this.onCollection(!currentCollection);
          this.showToast(!currentCollection);
        } else if (res.cancel) {}
      }
    })
  },

  // 弹窗提示
  showToast(result) {
    wx.showToast({
      title: result ? '收藏成功' : '取消成功',
      duration: 1000
    })
  },

  // 设置收藏
  onCollection: function(result) {
    let collection = wx.getStorageSync('collection');
    if (!collection) {
      collection = {};
    }
    collection[this.data.id] = result;
    this.setData({
      currentCollection: result
    });
    wx.setStorageSync('collection', collection);
  },

  //分享
  onShare() {
    let arr = ["分享给微信好友", "分享给qq好友", "分享到朋友圈"];
    wx.showActionSheet({
      itemList: arr,
      itemColor: '#405f80',
      success: (res) => {
        // res.tapIndex.数组元素，从0开始
        wx.showModal({
          title: '分享',
          showCancel: false,
          content: `${arr[res.tapIndex]}功能尚未开发,小程序暂不支持`,
        })
      }
    })
  },

  // 播放音乐
  onPlayVoice: function() {
    wx.playBackgroundAudio({
      dataUrl: this.data.news.music.url,
      title: this.data.news.music.title,
      coverImgUrl: this.data.news.music.coverImg,
      success: function() {
        console.log('播放成功');
      }
    });
  },

  // 暂停音乐
  onPauseVoice: function() {
    wx.pauseBackgroundAudio();
  }
})